<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }

    #box{
        width: 500px;
        height: 350px;
        margin: 0 auto;
        margin-top: 2em;
        border: 1px solid rebeccapurple;
        overflow: hidden;
    }

    #tab{
        width: 100%;
        height: 35px;
        display: flex;
    }

    #tab .item{
        width: 25%;
        text-align: center;
        line-height: 35px;
        border-right: 1px solid rebeccapurple;
        border-bottom: 1px solid rebeccapurple;
    }

    #tab .item:last-child{
        border-right: none;
    }

    #content,#content .item{
        width: 100%;
        height: 100%;
    }

    #content .item{
        text-align: center;
        line-height: 350px;
        display: none;
    }

    #tab .item.active{
        background-color: red;
        border-bottom:none;
        color: #fff;
    }

    #content .item.active{
        background-color: red;
        color: #fff;
        display: block;
    }
</style>
<body>
    <div id="box">
        <div id="tab">
            <div class="item active">1</div>
            <div class="item">2</div>
            <div class="item">3</div>
            <div class="item">4</div>
        </div>
        <div id="content">
            <div class="item active">1</div>
            <div class="item">2</div>
            <div class="item">3</div>
            <div class="item">4</div>
        </div>
    </div>
</body>
</html>

<script>
    // 通过id或者class名去获取相应节点
    let tab = document.getElementById('tab');// tab
    let TabItem = tab.getElementsByClassName('item');// tab里的子元素
    let content = document.getElementById('content');// 内容
    let ContentItem = content.getElementsByClassName('item');// 内容子元素

    // let active = document.getElementsByClassName('active');
    // active.classList.remove('active');
    // console.log(active)
    // 把tab的item循环出来
    for(var i = 0;i < TabItem.length;i++)
    {
        TabItem[i].index = i;
        TabItem[i].onclick = function()
        {
            // console.log(this);
            for(let j = 0;j < TabItem.length;j++)
            {
                // TabItem[j].className = 'item';
                TabItem[j].classList.remove('active');
                ContentItem[j].classList.remove('active');
            }

            // 报错：active是HTML集合，集合不存在classList
            // active.classList.remove('active');
            // console.log(i)

            // this.className += ' active';

            ContentItem[this.index].classList.add('active');
            this.classList.add('active');
        }
    }
</script>